package ink.tiptop.configuration;

import ink.tiptop.enums.EResp;
import ink.tiptop.common.cache.ICache;
import ink.tiptop.constant.AuthConst;
import ink.tiptop.exception.JDTException;
import ink.tiptop.exception.JDTExceptionMsg;
import ink.tiptop.utils.date.DateBaseHolder;
import ink.tiptop.utils.date.DateHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.format.DateTimeFormatter;

/**
 * @author ink.tiptop.zjf
 * @Title: Ticket
 * @Package ink.tiptop.common.interceptor
 * @Description: 自定义登陆拦截器
 * @date 2020-06-25 21:58
 */
@Slf4j
public class LogInterceptor extends HandlerInterceptorAdapter {

    /**
     * 在业务处理器处理请求之前被调用
     * 如果返回false
     *     从当前的拦截器往回执行所有拦截器的afterCompletion(),再退出拦截器链
     *
     * 如果返回true
     *    执行下一个拦截器,直到所有的拦截器都执行完毕
     *    再执行被拦截的Controller
     *    然后进入拦截器链,
     *    从最后一个拦截器往回执行所有的postHandle()
     *    接着再从最后一个拦截器往回执行所有的afterCompletion()
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws IOException {
        limitRequest(request);
        return true;
    }

    private void limitRequest(HttpServletRequest request) {
        String requestUri = request.getRequestURI().trim();
        String contextPath = request.getContextPath();
        String url = requestUri.substring(contextPath.length());

        if (url.equals("/zjfAuthUserInfo/login")) {
            // 是否失效
            Object val = cache.getVal(AuthConst.SESSION_ID, AuthConst.CACHE_TYPE_FORBID);
            if (val != null) {
                JDTException.throwException(JDTExceptionMsg.getError(EResp.EUserAuth.ERROR_LOGIN_TO_MANY));
            }
            cache.setVal(AuthConst.SESSION_ID, url, AuthConst.CACHE_TYPE_FORBID);
        }

        //Request time : 2020-07-25 16:21:58, Request url : /zjfAuthUserInfo/login , Request method,POST
        log.info("Request time : {}, Request url : {} , Request method,{}", DateHolder.now().format(
                DateTimeFormatter.ofPattern(DateBaseHolder.Pattern.Y_M_D_H_M_S.pattern))
                ,url,request.getMethod());
    }

    @Autowired
    private ICache cache;


    /**
     * 在业务处理器处理请求执行完成后,生成视图之前执行的动作
     * 可在modelAndView中加入数据，比如当前时间
     */
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        if(modelAndView != null){  //加入当前时间
            modelAndView.addObject("haha", "测试postHandle");
        }
    }
    /**
     * 在DispatcherServlet完全处理完请求后被调用,可用于清理资源等
     * 当有拦截器抛出异常时,会从当前拦截器往回执行所有的拦截器的afterCompletion()
     */
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }
}
